﻿var grid = null;
var PageSize = 20;
var url = "ActionInf.aspx?";
var permission = null;

$(document).ready(function () {
    permission = JSON.parse($("#hdPermission").val());
    grid = $("#maingrid").ligerGrid({
        columns: [
        { display: 'Action ID', name: 'ActID', width: 100, align: 'center'},
        { display: 'Action 描述', name: 'ActName', width: 170, align: 'left' },
        { display: 'Status', name: 'Flag', width: 60, align: 'center', hide: 'hide' },
        { display: '最后更新', name: 'Lpt', width: 150, align: 'left', isSort: false }, 
        { display: '操作人',name: 'Whom',width: 100,align: 'center'}],
        pageSize: PageSize,
        toolbar: {},
        url: url + "Action=GetList",
        width: '100%',
        height: '99%',
        dataAction: 'local',
        pageSizeOptions: [3,20, 25, 30, 35],
        pageStatMessage: 'Record:{from}-{to} Total:{total} Page Size:{pagesize}',
        checkbox: true,
        sortName: 'rID',
        sortOrder: 'ASC',
        rowAttrRender: function (item, rowid) {
            var color = "";
            if (item.Flag == "I") color = " my-disabled";
            return color;
        },
        onDblClickRow: function (row, rowindex, rowDomElement) {
            if (permission.isEdit) {
                showDetail({
                    RID: row.RID,
                    ActID: row.ActID,
                    ActName: row.ActName,
                    Flag: row.Flag
                });
            }
        }
    });
    //加载搜索框
    InitForm();

    //加载工具条
    loadToolbar();
})

//搜索条件
function InitForm() {
    $("#txtActID").ligerTextBox({
        label: "Action ID",
        labelWidth: 70
    });
    $("#txtActName").ligerTextBox({
        label: "Action 描述",
        labelWidth: 80
    });
    $("#BtnSearch").click(function () {
        BtnSearch_Click();
    });
}


//工具条
function loadToolbar() {
    var griditems = [];
    if (permission.isEdit) 
        griditems[griditems.length] = {click: toolbarClick,text: "新增",img: "../images/add.png",id: "Add"};
    if (permission.isActive) 
        griditems[griditems.length] = {click: toolbarClick,text: "有效",img: "../images/Active.png",id: "Enable" };
    if (permission.isInactive) 
        griditems[griditems.length] = {click: toolbarClick,text: "失效",img: "../images/Frozen.png",id: "Disable"};
    grid.toolbarManager.set('items', griditems);
}

//工具条事件
function toolbarClick(item) {
    switch (item.id) {
        case "Add":
            BtnAdd_Click();
            break;
        case "Enable":
            BtnActive_Click();
            break;
        case "Disable":
            BtnInactive_Click();
            break;
    }
}

//查询按钮
function BtnSearch_Click() {
    var txtActID = $("#txtActID").val();
    var txtActName = $("#txtActName").val();
    grid.set('parms', {
        ActID: txtActID,
        ActName: txtActName
    });
    grid.options.newPage = 1;
    grid.loadData();
}

//新增
function BtnAdd_Click() {
    showDetail({ RID: ''}, true);
}

//Enable
function BtnActive_Click() {
    ProcessData("A");
}

//Disable
function BtnInactive_Click() {
    ProcessData("I");
}

/**
* 改变状态
* @param {[type]} type A11 or A12
*/
function ProcessData(type) {
    var rids = GetClientRID();
    if (rids != "") {
        $.ajax({
            type: 'post',
            url: url + 'Action=Process&type=' + type + '&rids=' + rids,
            dataType: 'text',
            cache: false,
            success: function (msg) {
                if (msg == "") {
                    toastrSuccess("Processed successfully/处理成功!");
                    BtnSearch_Click();
                } else {
                    toastrError("Processed Failed/处理失败!<br/>" + msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                ShowError("ProcessData()", XMLHttpRequest, textStatus, errorThrown);
            }
        });
    }
}

//获取选中列表ID
function GetClientRID() {
    var rows = grid.getSelectedRows();
    if (!rows.length) {
        toastrWarning('Please select lines to be processed!<br/>请选择需要处理的行!');
        return "";
    }
    var ids = [];
    for (var i = 0; i < rows.length; i++) {
        ids.push(rows[i].RID);
    }
    return ids.join(',');
}

var detailWin = null,
    currentData = null;
/**
* 弹出编辑框
* @param  {[type]} data 当前row内容
* @return {[type]}      [description]
*/
function showDetail(data) {
    currentData = data;
    if (detailWin) {
        detailWin.show();
    } else {
        //创建表单结构
        var mainform = $("#mainform");
        mainform.ligerForm({
            inputWidth: 280,
            space: 30,
            fields: [
            { name: "RID", type: "hidden" },
            { name: "Flag1", type: "hidden" },
            { display: "Action ID", name: "ActID1", newline: true, labelWidth: 150, width: 220, type: "text" },
            { display: "Action Desc", name: "ActName1", newline: true, labelWidth: 150, width: 220, type: "text" }
            ]
        });


        detailWin = $.ligerDialog.open({
            title: "Action管理",
            target: $("#detail"),
            width: 450,
            height: 150,
            top: 120,
            allowClose: false,
            buttons: [
            { text: '保存', onclick: function () { save(); } }, 
            { text: '取消', onclick: function () { detailWin.hide(); HideTip(); }
            }]
        });
    }
    if (currentData.RID != '') {
        $("#RID").val(currentData.RID);
        $("#ActID1").val(currentData.ActID);
        $("#ActName1").val(currentData.ActName);
        $("#ActID1").ligerGetTextBoxManager().setDisabled();
        $("#Flag1").val(currentData.Flag);
        $("#ActName1").focus();
    } else {
        $("#RID").val('');
        $("#ActID1").val('');
        $("#ActID1").ligerGetTextBoxManager().setEnabled();
        $("#ActName1").val('');
        $("#Flag1").val("A");
        $("#ActID1").focus();
    }
    $("#ActID1").attr("maxlength", 3);
    $("#ActName1").attr("maxlength", 50);


    function save() {
        HideTip();
        currentData = currentData || {};
        currentData.RID = $("#RID").val();
        currentData.ActID = $.trim($("#ActID1").val());
        currentData.Flag = $("#Flag1").val();

        if (currentData.ActID == "") {
            $("#ActID1").ligerTip({
                content: "Cannot be blank/不允许为空!"
            });
            $("#ActID1").select();
            return false;
        } else if (currentData.ActID.length > 3) {
            $("#ActID1").ligerTip({
                content: "The maximum length is 3/最大长度3!"
            });
            $("#ActID1").select();
            return false;
        }

        currentData.ActName = $.trim($("#ActName1").val());
        if (currentData.ActName == "") {
            $("#ActName1").ligerTip({
                content: "Cannot be blank/不允许为空!"
            });
            $("#ActName1").select();
            return false;
        } else if (currentData.ActName.length > 50) {
            $("#ActName1").ligerTip({
                content: "The maximun length is 50/最大长度50!"
            });
            $("#ActName1").select();
            return false;
        }

        var _url = url + "Action=Save";
        $.ajax({
            cache: false,
            async: true,
            url: _url,
            data: currentData,
            dataType: 'text',
            type: 'post',
            success: function (res) {
                grid.loadData();
                switch (res) {
                    case "existed":
                        toastrWarning("操作编码或操作名称已存在，请尝试另一个!");
                        break;
                    case "successed":
                        toastrSuccess("保存成功!");
                        detailWin.hide();
                        break;
                    case "failed":
                        toastrError("保存失败!");
                        break;
                    default:
                        break;
                }
            },
            error: function (message) {
                if (message.responseText == "True") {
                    grid.loadData();
                    toastrSuccess('Saved/保存成功!');
                    detailWin.hide();
                } else {
                    toastrError('Error! Not saved/保存失败!');
                }
            }
        });
    }

    function HideTip() {
        $("#ActID1").ligerHideTip();
        $("#ActName1").ligerHideTip();
    }
}

/**
* 显示错误
* @param {[type]} fun            [description]
* @param {[type]} XMLHttpRequest [description]
* @param {[type]} textStatus     [description]
* @param {[type]} errorThrown    [description]
*/
function ShowError(fun, XMLHttpRequest, textStatus, errorThrown) {
    var mess = "出错了! 请联系管理员!<br/>";
    mess += "function:" + fun + "<br/>";
    mess += "XMLHttpRequest.status:" + XMLHttpRequest.status + "<br/>";
    mess += "XMLHttpRequest.readyState:" + XMLHttpRequest.readyState + "<br/>";
    mess += "textStatus:" + textStatus;
    toastrError(mess);
}